package com.dubbo.lian.cms.modules.app.service.impl;
 import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dubbo.lian.cms.modules.app.dto.HmScore;
import com.dubbo.lian.cms.modules.app.service.IFolderNoticeService;
import com.dubbo.lian.cms.modules.app.service.IUserdataService;
import com.dubbo.lian.cms.modules.app.FolderNotice;
import com.dubbo.lian.common.util.BaseR;
import com.dubbo.lian.cms.modules.app.User;
import com.dubbo.lian.cms.modules.app.dto.HmScoreR;
import com.dubbo.lian.cms.modules.app.mapper.UserMapper;
import com.dubbo.lian.cms.modules.app.service.IUserMissionService;
import com.dubbo.lian.cms.modules.app.service.IUserService;
import com.dubbo.lian.common.util.ReturnTemplateUtil;
import com.dubbo.lian.common.util.TimeUtil;
import com.dubbo.lian.common.util.VersionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 /**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author lian
 * @since 2016-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
     @Autowired
    IUserMissionService userMissionService;
    @Autowired
    IUserdataService userdataService;
    @Autowired
    IFolderNoticeService versionService;
     static final int IAQ_SCORE          = 15;//空气检测仪
    static final int SCALE_SCORE        = 15;//体脂秤
     static final int BMI_SCORE         = 5;//bim
    static final int BONE_SCORE        = 5;//骨量
    static final int FAT_SCORE         = 5;//脂肪
    static final int MBR_SCORE         = 5;//基础代谢率
    static final int MOISTURE_SCORE    = 5;//水分
    static final int MUSCLE_SCORE      = 5;//肌肉
    static final int PROTEIN_SCORE     = 5;//蛋白质
    static final int WEIGHT_SCORE      = 5;//重量分数
     static final int STEP_NUMBER_SCORE = 5;
     static final int MISSION_SCORE     = 5;
    static final int WEIGH_SCORE       = 5;
     static final int SOFTWARE_SCORE    = 15;//软件分数
     static final int STEP_NUMBER       = 6000;
     protected static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
     @Override
    public BaseR selectHmScore(JSONObject jsonObj) {
        long totalScore = 0;
         HmScoreR hmScoreR = new HmScoreR();
        HmScore obj = JSON.parseObject(jsonObj.toJSONString(), HmScore.class);
        String userid = obj.getUserid();
        HmScore.Activity activity = obj.getActivity();
        HmScore.Hardware hardware = obj.getHardware();
        HmScore.UserData userData = obj.getUserData();
        HmScore.Other other = obj.getOther();
         try {
            HmScoreR.Hardware hardwareR = calculationHardware(hardware);
             HmScoreR.UserData userDataR = calculationUserData(userData);
             HmScoreR.Activity activityR = calculationActivity(activity);
             HmScoreR.Habit habitR = calculationHabit(userid);
             HmScoreR.Other otherR = calculationOther(other);
             totalScore = calculationTotalScore(hardwareR.getTotalScore(),userDataR.getTotalScore(),activityR.getTotalScore(),habitR.getTotalScore(),otherR.getTotalScore());
             hmScoreR.setHardware(hardwareR);
            hmScoreR.setUserData(userDataR);
            hmScoreR.setActivity(activityR);
            hmScoreR.setHabit(habitR);
            hmScoreR.setOther(otherR);
            hmScoreR.setUserHmScore(totalScore);
         } catch (Exception e) {
            return ReturnTemplateUtil.errReturn(e.getMessage()+"||"+jsonObj.toJSONString(),logger);
        }
         return ReturnTemplateUtil.returnOfObject(hmScoreR);
    }
     private long calculationTotalScore(Long hardwareScore, Long userDataScore, Long activityScore, Long habitScore, Long otherTotalScore) {
         long totalScore;
         totalScore = hardwareScore
                +userDataScore
                +activityScore
                +habitScore
                +otherTotalScore;
        return totalScore;
    }
     private HmScoreR.Other calculationOther(HmScore.Other other) {
        int totalScore = 0;
        HmScoreR.Other otherR = new HmScoreR.Other();
        Long isLatestVersion = 0L;
        String localVersion = "";
        long SoftwareScore = 0;
        if (other!=null) {
            if(other.getVersion()!=null&&!"".equals(other.getVersion())){
//                FolderNotice versionAr = new FolderNotice();
//                FolderNotice versionEntity = versionAr.selectById(3);
//                String onlineVersion = versionEntity.getIcon();
//                EntityWrapper ew = new EntityWrapper();
//                FolderNotice version = new FolderNotice();
//                version.setId(3);
//                ew.setEntity(version);
                FolderNotice folderNotice = versionService.selectById(3);
                String onlineVersion = folderNotice.getIcon();
                localVersion = other.getVersion();
                boolean appNewVersion = VersionUtil.isAppNewVersion(localVersion, onlineVersion);
                 if(appNewVersion==false){
                    SoftwareScore = SOFTWARE_SCORE;
                    totalScore = totalScore + SOFTWARE_SCORE;
                }
            }else{
                isLatestVersion = other.getIsLatestVersion();
                if(isLatestVersion==1){
                    SoftwareScore = SOFTWARE_SCORE;
                    totalScore = totalScore + SOFTWARE_SCORE;
                }
            }
        }
         otherR.setSoftwareScore(SoftwareScore);
        otherR.setTotalScore((long)totalScore);
        return otherR;
    }
     private HmScoreR.UserData calculationUserData(HmScore.UserData userData) throws Exception{
        int totalScore = 0;
        HmScoreR.UserData userDataR = new HmScoreR.UserData();
        long bmi = 0;
        long bone = 0;
        long fat = 0;
        long mbr = 0;
        long moisture = 0;
        long muscle = 0;
        long protein = 0;
        long weight = 0;
        if (userData!=null) {
            bmi = userData.getBmi();
            bone = userData.getBone();
            fat = userData.getFat();
            mbr = userData.getMbr();
            moisture = userData.getMoisture();
            muscle = userData.getMuscle();
            protein = userData.getProtein();
            weight = userData.getWeight();
            if (bmi==1){
                totalScore = totalScore + BMI_SCORE;
            }
            if (bone==1){
                totalScore = totalScore + BONE_SCORE;
            }
            if (fat==1){
                totalScore = totalScore + FAT_SCORE;
            }
            if (mbr==1){
                totalScore = totalScore + MBR_SCORE;
            }
            if (moisture==1){
                totalScore = totalScore + MOISTURE_SCORE;
            }
            if (muscle==1){
                totalScore = totalScore + MUSCLE_SCORE;
            }
            if (protein==1){
                totalScore = totalScore + PROTEIN_SCORE;
            }
            if (weight==1){
                totalScore = totalScore + WEIGHT_SCORE;
            }
        }
        userDataR.setBmiScore(setScore(bmi,BMI_SCORE));
        userDataR.setBoneScore(setScore(bone,BONE_SCORE));
        userDataR.setFatScore(setScore(fat,FAT_SCORE));
        userDataR.setMbrScore(setScore(mbr,MBR_SCORE));
        userDataR.setMoistureScore(setScore(moisture,MOISTURE_SCORE));
        userDataR.setMuscleScore(setScore(muscle,MUSCLE_SCORE));
        userDataR.setProteinScore(setScore(protein,PROTEIN_SCORE));
        userDataR.setWeightScore(setScore(weight,WEIGHT_SCORE));
        userDataR.setTotalScore((long)totalScore);
        return userDataR;
    }
     private HmScoreR.Activity calculationActivity(HmScore.Activity activity) throws Exception{
        int totalScore = 0;
        long step = 0;
        HmScoreR.Activity activityR = new HmScoreR.Activity();
        HmScoreR.Activity.Step stepR = new HmScoreR.Activity.Step();
        if (activity!=null) {
            step = activity.getStep();
            if(step>=STEP_NUMBER){
                totalScore = totalScore + STEP_NUMBER_SCORE;
            }
        }
        stepR.setStepNumber((long)STEP_NUMBER);
        stepR.setStepNumberScore(step>=STEP_NUMBER?STEP_NUMBER_SCORE:0L);
        activityR.setStep(stepR);
        activityR.setTotalScore((long)totalScore);
        return activityR;
    }
     private HmScoreR.Habit calculationHabit(String userid) throws Exception{
        int totalScore = 0;
         HmScoreR.Habit habitR = new HmScoreR.Habit();
        HmScoreR.Habit.Mission missionR = new HmScoreR.Habit.Mission();
         boolean isHaveMission= false;
        int missionCount = 0;
        int unfinished = 0;
        int finished = 0;
        int dataCount = 0;
        long weighScore = 0;
        try {
            EntityWrapper isHaveMissionEw = new EntityWrapper();
            isHaveMissionEw.where("userid={0}",userid);
            missionCount = userMissionService.selectCount(isHaveMissionEw);
            if (missionCount > 0) {
                isHaveMission=true;
            }
             EntityWrapper unfinishedMissionCountEw = new EntityWrapper();
            unfinishedMissionCountEw.where("userid={0}",userid);
            unfinishedMissionCountEw.and("time={0}", TimeUtil.getDate());
            unfinishedMissionCountEw.and("is_complete={0}",0);
            unfinishedMissionCountEw.and("is_del={0}",0);
            unfinished = userMissionService.selectCount(unfinishedMissionCountEw);
             EntityWrapper finishedMissionCountEw = new EntityWrapper();
            finishedMissionCountEw.where("userid={0}",userid);
            finishedMissionCountEw.and("time={0}", TimeUtil.getDate());
            finishedMissionCountEw.and("is_complete={0}",1);
            finishedMissionCountEw.and("is_del={0}",0);
            finished = userMissionService.selectCount(finishedMissionCountEw);
             EntityWrapper dataEw = new EntityWrapper();
            dataEw.where("userid={0}",userid);
            dataEw.and("DATE_FORMAT(createtime,\"%Y-%m-%d\")={0}",TimeUtil.getDate());
            dataCount = userdataService.selectCount(dataEw);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        if (unfinished<=0&&isHaveMission&&finished>0){
            totalScore = totalScore + MISSION_SCORE;
        }
        if (dataCount>=1){
            weighScore = WEIGH_SCORE;
            totalScore = totalScore + WEIGH_SCORE;
        }
        missionR.setIsHaveMission(isHaveMission);
        missionR.setMissionScore(((unfinished<=0)&&isHaveMission&&(finished>0))?MISSION_SCORE:0L);
        habitR.setMission(missionR);
        habitR.setWeighScore(weighScore);
        habitR.setTotalScore((long)totalScore);
        return habitR;
    }
     private HmScoreR.Hardware calculationHardware(HmScore.Hardware hardware) throws Exception{
        HmScoreR.Hardware hardwareR = new HmScoreR.Hardware();
        int totalScore = 0;
        long iaq = 0;
        long scale = 0;
        if(hardware!=null){
            iaq = hardware.getIaq();
            scale = hardware.getScale();
            if(iaq==1){
                totalScore = totalScore + IAQ_SCORE;
            }
            if(scale==1){
                totalScore = totalScore + SCALE_SCORE;
            }
        }
        hardwareR.setIaqScore(setScore(iaq,IAQ_SCORE));
        hardwareR.setScaleScore(setScore(scale,SCALE_SCORE));
        hardwareR.setTotalScore((long)totalScore);
        return hardwareR;
    }
     private long setScore(long judgeObj,long score) {
        long scoreR;
        if(judgeObj==1){
            scoreR=score;
        }else{
            scoreR=0L;
        }
        return scoreR;
    }
     public static void main(String[] args) {
        int TOTAL_SCORE = 0;
        TOTAL_SCORE =   IAQ_SCORE
                        +SCALE_SCORE
                        +BMI_SCORE
                        +BONE_SCORE
                        +FAT_SCORE
                        +MBR_SCORE
                        +MOISTURE_SCORE
                        +MUSCLE_SCORE
                        +PROTEIN_SCORE
                        +WEIGHT_SCORE
                        +STEP_NUMBER_SCORE
                        +MISSION_SCORE
                        +WEIGH_SCORE
                        +SOFTWARE_SCORE;
        System.out.println(TOTAL_SCORE);
    }
 }
